<template>
  <div class="flex h-full">
    <a-card class="mr-2" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column' }">
      <PatientListDrawer
        :patient-list="dataSource"
        :loading="loading"
        :border-bottom="false"
        :selected-item="store.currentPatient"
        :search-show="true"
        :time-val="store.radioKey === 1 ? 'outHospitalDate' : 'admissionTime'"
        @scroll="onScroll"
        @select="onSelectPatient"
        @refresh="getData()"
      >
        <template #search>
          <SelectArea v-model:value="searchParams.bqbh" use-cache class="w-full px-2" post-url @change="getData(), (store.currentPatient = {})" />
        </template>
        <template #tabRadio>
          <div class="p-2 w-full -mt-2">
            <a-input-search
              v-model:value="searchParams.searchKey"
              class="w-full"
              placeholder="床位号/姓名/助记码"
              @search="getData()"
              @change="onInputChange"
            />
          </div>
          <a-radio-group v-model:value="store.radioKey" button-style="solid" class="w-full px-3" @change="getData()">
            <a-radio-button :value="0" class="w-1/2 text-center">在院</a-radio-button>
            <a-radio-button :value="1" class="w-1/2 text-center">已出院</a-radio-button>
          </a-radio-group>
        </template>
      </PatientListDrawer>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="store.currentPatient" @change="getData()">
        <template #prefix>
          <div class="text-2xl pr-4 text-primary font-semibold min-w-10">{{ store.currentPatient?.lastBedCode || '- ' }}床</div>
        </template>
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue label="住院科室" :width="200" :value="store.currentPatient.ksmc" />
            <LabelValue label="部位" :width="220" :value="store.currentPatient.bws" />
            <LabelValue label="住院号" :width="200" :value="store.currentPatient.admissionCode" />
            <LabelValue label="医疗类别" :width="200" :value="store.currentPatient.inpTypeName" />
            <AllergyHistory
              label="过敏史"
              class="mr-2"
              :width="260"
              :value="store.currentPatient.brGms"
              :patient-info="store.currentPatient"
              @success="(e) => (store.currentPatient.brGms = e)"
            />
            <!-- <LabelValue label="过敏史"labelClass="w-16"  :width="200" :value="store.currentPatient.brGms" /> -->
            <LabelValue label="付费方式" :width="200" :value="store.currentPatient.paymentTypeName" />
          </div>
          <div class="flex items-center">
            <LabelValue label="住院病区" :width="200" :value="store.currentPatient.wardName" />
            <LabelValue label="入区时间" :width="220" :value="store.currentPatient.lastDeptRegTime" />
            <LabelValue label="账户余额" :width="200" :value="formatAmount(store.currentPatient.zhye) + '元'" />
            <LabelValue label="累计预收款" :width="200" :value="formatAmount(store.currentPatient.ljysk) + '元'" />
            <LabelValue label="入院诊断" class="mr-2" :width="260" tooltip :value="store.currentPatient.ryzd" />
            <LabelValue label="住院天数" :width="160" :value="store.currentPatient.zyts" />
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-hidden" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <a-tabs
            v-model:active-key="tabsKey"
            class="h-full workstation-tabs"
            destroy-inactive-tab-pane
            :class="{ 'tabs-disabled': !store.currentPatient?.inplsh }"
            @change="onChangeTabs"
          >
            <a-tab-pane key="医嘱" tab="医嘱">
              <TabDoctorAdvice :page-loading="loading" />
            </a-tab-pane>
            <a-tab-pane v-if="systemConfig.isInspect" key="检查" tab="检查">
              <TabCheck />
            </a-tab-pane>
            <a-tab-pane v-if="systemConfig.isInspection" key="检验" tab="检验">
              <TabLaboratory />
            </a-tab-pane>
            <a-tab-pane key="医技" tab="医技">
              <TabTechnology />
            </a-tab-pane>
            <a-tab-pane key="手术" tab="手术">
              <TabOperation :br-id="store.currentPatient.brId" />
            </a-tab-pane>
            <a-tab-pane key="诊断" tab="诊断">
              <TabDispose />
            </a-tab-pane>
            <a-tab-pane v-if="systemConfig.isEleCase" key="住院病历" tab="住院病历">
              <TabEMR emr-type="2" :current-patient="store.currentPatient" />
            </a-tab-pane>
            <a-tab-pane key="病案首页" tab="病案首页">
              <MedicalRecord :inplsh="store.currentPatient.inplsh" />
            </a-tab-pane>
            <a-tab-pane key="病案附页" tab="病案附页">
              <AnhuiAppendix :inplsh="store.currentPatient.inplsh" />
            </a-tab-pane>
            <a-tab-pane key="体温脉搏" tab="体温脉搏">
              <TabTemperature :key="store.currentPatient.inplsh" :inplsh="store.currentPatient.inplsh" />
            </a-tab-pane>
            <a-tab-pane key="血糖监测" tab="血糖监测">
              <TabBloodSugar :key="store.currentPatient.inplsh" :inplsh="store.currentPatient.inplsh" />
            </a-tab-pane>
            <!-- <a-tab-pane key="护理文书" tab="护理文书"> 护理文书 </a-tab-pane> -->
            <a-tab-pane key="门诊履历" tab="门诊履历"> <HistoryCase /> </a-tab-pane>
            <a-tab-pane key="费用查询" tab="费用查询">
              <TabCostQuery />
            </a-tab-pane>
          </a-tabs>
        </a-card>
        <a-card
          v-if="tabsKey === '医技'"
          class="w-72 ml-2 history-card"
          :class="historyExpand ? 'history-expand' : ''"
          :body-style="{ paddingTop: 0, height: '100%' }"
        >
          <div class="history-expand-btn" @click="() => (historyExpand = !historyExpand)">
            <DoubleLeftOutlined v-if="historyExpand" />
            <DoubleRightOutlined v-else />
          </div>
          <div v-if="historyExpand" class="pt-12 text-primary font-semibold">历史</div>
          <a-tabs v-model:active-key="activeKeyPart" centered class="h-full">
            <a-tab-pane key="1">
              <template #tab>
                <div class="px-2 text-center">历史</div>
              </template>
              <div class="overflow-auto" style="height: calc(100vh - 200px)">
                <HistoryPart :open="historyExpand" :active-key="activeKeyPart" />
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
    </div>
    <DoctorCrisisModal />
  </div>
</template>

<script setup>
import { onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { debounce } from 'lodash-es'
import { message } from 'ant-design-vue'
import { DoubleRightOutlined, DoubleLeftOutlined } from '@ant-design/icons-vue'
import { formatAmount } from '@/utils/format'
import useUserStore from '@/store/user'
import { getSystemConfig } from '@/utils/systemConfig'
import MedicalRecord from '@/components/MedicalRecord'
import DoctorCrisisModal from '@/views/workstation-inspect/workstation/components/DoctorCrisisModal/index.vue'
import TabDispose from './components/TabDispose'
import TabCheck from './components/TabCheck'
import TabLaboratory from './components/TabLaboratory'
import TabTechnology from './components/TabTechnology'
import TabTemperature from './components/TabTemperature'
import HistoryCase from './components/HistoryCase'
import TabDoctorAdvice from './components/TabDoctorAdvice'
import TabOperation from './components/TabOperation'
import TabEMR from './components/TabEMR'
import TabCostQuery from './components/TabCostQuery'
import TabBloodSugar from './components/TabBloodSugar'
import HistoryPart from './components/TabTechnology/HistoryPart'
import useStore from './store'

const router = useRouter()
const store = useStore()
const tabsKey = ref(router.currentRoute.value.query.tab || '医嘱')
const routerInplsh = ref(router.currentRoute.value.query.inplsh || '')
const { empId } = useUserStore()
const searchParams = ref({
  searchKey: '',
  bqbh: ''
})

const systemConfig = {
  isEleCase: getSystemConfig('INP_DOCTOR_SHOW_EMR') === '1', // 显示住院病历
  isInspect: getSystemConfig('IS_INP_DOCTOR_RIS') === '1', // 检查
  isInspection: getSystemConfig('IS_INP_DOCTOR_LIS') === '1' // 检验
}

const dataSource = ref([])
const historyExpand = ref(true)
const activeKeyPart = ref('1')
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(20)
const total = ref(0)
const hasMore = ref(true)
const onInputChange = debounce(() => getData(), 300)

// 获取列表数据
const getData = async (isLoadMore = false) => {
  // 如果没有更多数据且是加载更多操作则直接返回
  if (!hasMore.value && isLoadMore) return

  // 如果不是加载更多则重置页码和数据
  if (!isLoadMore) {
    pageNum.value = 1
    dataSource.value = []
  }

  // 防止重复请求
  if (loading.value) return
  loading.value = true

  const {
    code,
    msg,
    data,
    total: totalCount
  } = await post('/inp/zydj/getInpRecordList', {
    statuss: store.radioKey === 0 ? [0, 2] : [1],
    empId,
    bqbh: searchParams.value.bqbh,
    pyjm: searchParams.value.searchKey,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  })
  loading.value = false
  if (code !== 0) return message.error(msg)

  // 更新数据源
  dataSource.value = isLoadMore ? [...dataSource.value, ...data] : data
  if (store.radioKey === 1) {
    dataSource.value = dataSource.value.map((item) => {
      if (item.chargeStatus === 1) {
        item.outHospitalDate = item.chargeTime
      } else if (item.chargeStatus === 3) {
        item.outHospitalDate = item.creditTime
      } else {
        item.outHospitalDate = item.dischargeTime
      }
      return item
    })
  }
  total.value = totalCount

  // 判断是否还有更多数据
  hasMore.value = dataSource.value.length < total.value

  // 处理选中逻辑
  !isLoadMore && handlePatientSelection(data)
}

// 处理病人选中逻辑
const handlePatientSelection = (data) => {
  if (routerInplsh.value) {
    const index = data.findIndex((item) => item.inplsh === routerInplsh.value)
    if (index > -1) {
      onSelectPatient(data[index])
      return
    }
  }

  if (store.currentPatient.inplsh) {
    const index = data.findIndex((item) => item.inplsh === store.currentPatient.inplsh)
    if (index > -1) {
      onSelectPatient(data[index])
    } else {
      data[0] && onSelectPatient(data[0])
    }
  } else {
    data[0] && onSelectPatient(data[0])
  }
}
//切换Tab标签
const onChangeTabs = async () => {
  const query = routerInplsh.value ? { tab: tabsKey.value, inplsh: routerInplsh.value } : { tab: tabsKey.value }
  router.push({
    path: '/in-doctor/workstation',
    query
  })
}

const onSelectPatient = (patient) => {
  store.currentPatient = patient
}
onMounted(() => {
  store.currentPatient = {}
  getData()
})

onUnmounted(() => {
  store.currentPatient = {}
})

// 滚动加载更多
const onScroll = debounce((e) => {
  const { scrollTop, clientHeight, scrollHeight } = e.target
  const scrollDistance = scrollHeight - scrollTop - clientHeight

  // 距离底部100px时加载更多
  if (scrollDistance <= 100 && !loading.value && hasMore.value) {
    pageNum.value++
    getData(true)
  }
}, 100)
</script>
<style lang="less" scoped>
.tabs-disabled {
  cursor: not-allowed;
  filter: opacity(0.5);
  pointer-events: none;
}
:deep(.ant-spin-container) {
  width: 100%;
  height: 100%;
}
:deep(.workstation-tabs) {
  .ant-tabs-tab {
    padding: 12px 32px;
  }
  .ant-tabs-tab + .ant-tabs-tab {
    margin: 0 16px;
  }
  // & > .ant-tabs-nav {
  //   .ant-tabs-tab:nth-child(4) {
  //     position: relative;
  //     &::after {
  //       position: absolute;
  //       top: 0;
  //       right: -16px;
  //       width: 1px;
  //       height: 100%;
  //       background: #f0f0f0;
  //       content: '';
  //     }
  //   }
  // }
  & > .ant-tabs-content-holder {
    height: 100%;
    .ant-tabs-content {
      height: 100% !important;
    }
  }
}

.history-card {
  transition: all 0.3s;
}

.history-expand {
  width: 56px !important;
  :deep(.ant-tabs) {
    visibility: hidden;
  }
}
.history-expand-btn {
  position: absolute;
  top: 4px;
  right: 12px;
  z-index: 99;
  padding: 8px;
  color: var(--primary-color);
  background-color: var(--secondary-color);
  border-radius: 8px;
  cursor: pointer;
}
</style>
